package org.fujene.balancer;

import java.net.UnknownHostException;
import java.util.TreeSet;

import org.fujene.communicate.node.Node;
import org.msgpack.rpc.Client;

public class RoundRobinBalancer implements SearchBalancer{
	private TreeSet<Node> nodes;
	private Node currentNode;
	private int indexPort;
	private int searchPort;
	private int contentNum;
	private int appendixNum;

	public RoundRobinBalancer(int indexPort, int searchPort, int contentNum, int appendixNum){
		this.indexPort = indexPort;
		this.searchPort = searchPort;
		this.contentNum = contentNum;
		this.appendixNum = appendixNum;
	}

	@Override
	public void refreshNodes(TreeSet<Node> nodes){
		this.nodes = nodes;
	}

	@Override
	public void index(String... contents){
		if(contents.length == contentNum + appendixNum){
			// Round-robin
			if(currentNode.equals(nodes.last()))
				currentNode = nodes.first();
			else currentNode = nodes.higher(currentNode);

			try{
				Client client = new Client(currentNode.getAddr(), indexPort);
				if(client != null){
					client.callApply("index", contents);
					client.close();
				}
			}catch(UnknownHostException e){}
		}
	}

	@Override
	public void search(String query){
		// Round-robin
		if(currentNode.equals(nodes.last()))
			currentNode = nodes.first();
		else currentNode = nodes.higher(currentNode);

		try{
			Client client = new Client(currentNode.getAddr(), searchPort);
			if(client != null){
				client.callApply("search", new Object[]{ query });
				client.close();
			}
		}catch(UnknownHostException e){}
	}
}
